
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>如何使用 Apache 和 mod_wsgi 托管 Django &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../../" src="../../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../../genindex.html" />
    <link rel="search" title="搜索" href="../../../search.html" />
    <link rel="next" title="Apache 利用 Django 的用户数据库进行验证" href="apache-auth.html" />
    <link rel="prev" title="如何用 uWSGI 托管 Django" href="uwsgi.html" />



 
<script src="../../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../../index.html">Home</a>  |
        <a title="Table of contents" href="../../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../../genindex.html">Index</a>  |
        <a title="Module index" href="../../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="uwsgi.html" title="如何用 uWSGI 托管 Django">previous</a>
     |
    <a href="../../index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="apache-auth.html" title="Apache 利用 Django 的用户数据库进行验证">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="howto-deployment-wsgi-modwsgi">
            
  <div class="section" id="s-how-to-use-django-with-apache-and-mod-wsgi">
<span id="how-to-use-django-with-apache-and-mod-wsgi"></span><h1>如何使用 Apache 和 <code class="docutils literal notranslate"><span class="pre">mod_wsgi</span></code> 托管 Django<a class="headerlink" href="#how-to-use-django-with-apache-and-mod-wsgi" title="永久链接至标题">¶</a></h1>
<p>利用 <a class="reference external" href="https://httpd.apache.org/">Apache</a> 和 <a class="reference external" href="https://modwsgi.readthedocs.io/en/develop/">mod_wsgi</a> 在生产环境部署已经过充分测试。</p>
<p>mod_wsgi 是一个 Apache 模块，它可以管理任何 Python <a class="reference external" href="https://wsgi.readthedocs.io/en/latest/">WSGI</a> 应用，包括 Django。Django 支持所有支持 mod_wsgi 的 Apache 版本。</p>
<p><a class="reference external" href="https://modwsgi.readthedocs.io/">官方 mod_wsgi 文档</a> 介绍了如何使用 mod_wsgi 的全部细节。你可能更喜欢从 <a class="reference external" href="https://modwsgi.readthedocs.io/en/develop/installation.html">安装和配置文档</a> 开始。</p>
<div class="section" id="s-basic-configuration">
<span id="basic-configuration"></span><h2>基础配置<a class="headerlink" href="#basic-configuration" title="永久链接至标题">¶</a></h2>
<p>一旦你安装了 mod_wsgi 并且启用了它，请在你的Apache服务器的 <a class="reference external" href="https://cwiki.apache.org/confluence/display/httpd/DistrosDefaultLayout">httpd.conf</a> 文件中添加如下内容。</p>
<div class="highlight-apache notranslate"><div class="highlight"><pre><span></span><span class="nb">WSGIScriptAlias</span> / <span class="sx">/path/to/mysite.com/mysite/wsgi.py</span>
<span class="nb">WSGIPythonHome</span> <span class="sx">/path/to/venv</span>
<span class="nb">WSGIPythonPath</span> <span class="sx">/path/to/mysite.com</span>

<span class="nt">&lt;Directory</span> <span class="s">/path/to/mysite.com/mysite</span><span class="nt">&gt;</span>
<span class="nt">&lt;Files</span> <span class="s">wsgi.py</span><span class="nt">&gt;</span>
<span class="nb">Require</span> <span class="k">all</span> granted
<span class="nt">&lt;/Files&gt;</span>
<span class="nt">&lt;/Directory&gt;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">WSGIScriptAlias</span></code> 行的第一项是你所期望的应用所在的基础 URL 路径（ <code class="docutils literal notranslate"><span class="pre">/</span></code> 根 url），第二项是 &quot;WSGI 文件&quot; 的位置——一般位于项目包之内（本例中是 <code class="docutils literal notranslate"><span class="pre">mysite</span></code>）。这告诉 Apache 用该文件中定义的 WSGI 应用响应指定 URL 下的请求。</p>
<p>如果你在某个 <code class="xref py py-mod docutils literal notranslate"><span class="pre">virtual</span> <span class="pre">environment</span> <span class="pre">1</span></code> 内为应用安装项目的 Python 依赖，将该 virtualenv 的路径添加至 <code class="docutils literal notranslate"><span class="pre">WSGIPythonHome</span></code> 。参考 <a class="reference external" href="https://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html">mod_wsgi virtualenv guide</a> 指南获取更多细节。</p>
<p><code class="docutils literal notranslate"><span class="pre">WSGIPythonPath</span></code> 行确保你的项目包能从 Python path 导入；换句话说， <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">mysite</span></code> 能正常工作。</p>
<p><code class="docutils literal notranslate"><span class="pre">1</span></code> 片段确保 Apache 能访问文件 <code class="file docutils literal notranslate"><span class="pre">wsgi.py</span></code> 文件。</p>
<p>下一步，我们需要确认 <code class="file docutils literal notranslate"><span class="pre">wsgi.py</span></code> 文件包含一个 WSGI 应用对象。从 Django 1.4 起， <a class="reference internal" href="../../../ref/django-admin.html#django-admin-startproject"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">startproject</span></code></a> 会自动创建；换而言之，你无需手动创建。查阅 <a class="reference internal" href="index.html"><span class="doc">WSGI&nbsp;概述文档</span></a> 获取你需要配置的默认内容，以及其它可配置项。</p>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p>如果多个 Django 站点运行在同一 mod_wsgi 进程，它们会共用最先启动的站点配置。能通过以下修改改变行为:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="s2">&quot;DJANGO_SETTINGS_MODULE&quot;</span><span class="p">,</span> <span class="s2">&quot;{{ project_name }}.settings&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">wsgi.py</span></code> 中也这么改:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">&quot;DJANGO_SETTINGS_MODULE&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;{{ project_name }}.settings&quot;</span>
</pre></div>
</div>
<p class="last">或通过 <a class="reference internal" href="#daemon-mode"><span class="std std-ref">使用 mod_wsgi 的后台模式</span></a> 确保每个站点都运行于独立的后台进程。</p>
</div>
<div class="admonition-fixing-unicodeencodeerror-for-file-uploads admonition">
<p class="first admonition-title">为文件上传修复 <code class="docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></p>
<p>上传名称包含非 ASCII 字符的文件时，若抛出 <code class="docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code>，确认 Apache 是否被正确配置，能接受非 ASCII 文件名:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">export</span> <span class="n">LANG</span><span class="o">=</span><span class="s1">&#39;en_US.UTF-8&#39;</span>
<span class="n">export</span> <span class="n">LC_ALL</span><span class="o">=</span><span class="s1">&#39;en_US.UTF-8&#39;</span>
</pre></div>
</div>
<p>常见的配置文件路径是 <code class="docutils literal notranslate"><span class="pre">/etc/apache2/envvars</span></code>。</p>
<p class="last">参考 Unicode 参考指引的 <a class="reference internal" href="../../../ref/unicode.html#unicode-files"><span class="std std-ref">文件</span></a> 章节获取细节信息。</p>
</div>
</div>
<div class="section" id="s-using-mod-wsgi-daemon-mode">
<span id="s-daemon-mode"></span><span id="using-mod-wsgi-daemon-mode"></span><span id="daemon-mode"></span><h2>使用 <code class="docutils literal notranslate"><span class="pre">mod_wsgi</span></code> 后台模式<a class="headerlink" href="#using-mod-wsgi-daemon-mode" title="永久链接至标题">¶</a></h2>
<p>&quot;Daemon mode&quot; 是运行 mod_wsgi 的推荐模式（在非 Windows 平台上）。为了创建必要的后台进程组并在其中运行 Django 实例，你需要添加合适的 <code class="docutils literal notranslate"><span class="pre">WSGIDaemonProcess</span></code> 和 <code class="docutils literal notranslate"><span class="pre">WSGIProcessGroup</span></code> 指令。上述配置在你使用后台模式时需要点小修改，即你不能使用 <code class="docutils literal notranslate"><span class="pre">WSGIPythonPath</span></code>；作为替换，你要在 <code class="docutils literal notranslate"><span class="pre">WSGIDaemonProcess</span></code> 中添加 <code class="docutils literal notranslate"><span class="pre">python-path</span></code> 选项，例如：</p>
<div class="highlight-apache notranslate"><div class="highlight"><pre><span></span><span class="nb">WSGIDaemonProcess</span> example.com python-home=/path/to/venv python-path=/path/to/mysite.com
<span class="nb">WSGIProcessGroup</span> example.com
</pre></div>
</div>
<p>如果你想在子目录中开放你的项目（本例中 <code class="docutils literal notranslate"><span class="pre">https://example.com/mysite</span></code>），你可在上述配置中添加 <code class="docutils literal notranslate"><span class="pre">WSGIScriptAlias</span></code>：</p>
<div class="highlight-apache notranslate"><div class="highlight"><pre><span></span><span class="nb">WSGIScriptAlias</span> <span class="sx">/mysite</span> <span class="sx">/path/to/mysite.com/mysite/wsgi.py</span> process-group=example.com
</pre></div>
</div>
<p>参考官方 mod_wsgi 文档获取 <a class="reference external" href="https://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html#delegation-to-daemon-process">配置后台模式的细节</a>。</p>
</div>
<div class="section" id="s-serving-files">
<span id="s-id1"></span><span id="serving-files"></span><span id="id1"></span><h2>提供文件服务<a class="headerlink" href="#serving-files" title="永久链接至标题">¶</a></h2>
<p>Django 本身并不提供文件服务；他将这个职责交给了你选择的 Web 服务器。</p>
<p>我们推荐使用一个独立的 Web 服务器，即其未运行 Django——仅用于媒体服务。以下是一些不错的选项：</p>
<ul class="simple">
<li><a class="reference external" href="https://nginx.org/en/">Nginx</a></li>
<li>一个 <a class="reference external" href="https://httpd.apache.org/">Apache</a> 的朴素版本</li>
</ul>
<p>然而，若你别无选择，只能在与 Django 相同的 Apache <code class="docutils literal notranslate"><span class="pre">VirtualHost</span></code> 上提供媒体文件，你可以让 Apache 为一些 URL 提供静态媒体服务，其它的用 mod_wsgi 接口传递给 Django。</p>
<p>本例在站点根目录配置 Django，但以静态文件的形式提供 <code class="docutils literal notranslate"><span class="pre">robots.txt</span></code>， <code class="docutils literal notranslate"><span class="pre">favicon.ico</span></code> 以及 <code class="docutils literal notranslate"><span class="pre">/static/</span></code> 和 <code class="docutils literal notranslate"><span class="pre">/media/</span></code> 中的内容。其它所有 URL 以 mod_wsgi 提供服务：</p>
<div class="highlight-apache notranslate"><div class="highlight"><pre><span></span><span class="nb">Alias</span> <span class="sx">/robots.txt</span> <span class="sx">/path/to/mysite.com/static/robots.txt</span>
<span class="nb">Alias</span> <span class="sx">/favicon.ico</span> <span class="sx">/path/to/mysite.com/static/favicon.ico</span>

<span class="nb">Alias</span> <span class="sx">/media/</span> <span class="sx">/path/to/mysite.com/media/</span>
<span class="nb">Alias</span> <span class="sx">/static/</span> <span class="sx">/path/to/mysite.com/static/</span>

<span class="nt">&lt;Directory</span> <span class="s">/path/to/mysite.com/static</span><span class="nt">&gt;</span>
<span class="nb">Require</span> <span class="k">all</span> granted
<span class="nt">&lt;/Directory&gt;</span>

<span class="nt">&lt;Directory</span> <span class="s">/path/to/mysite.com/media</span><span class="nt">&gt;</span>
<span class="nb">Require</span> <span class="k">all</span> granted
<span class="nt">&lt;/Directory&gt;</span>

<span class="nb">WSGIScriptAlias</span> / <span class="sx">/path/to/mysite.com/mysite/wsgi.py</span>

<span class="nt">&lt;Directory</span> <span class="s">/path/to/mysite.com/mysite</span><span class="nt">&gt;</span>
<span class="nt">&lt;Files</span> <span class="s">wsgi.py</span><span class="nt">&gt;</span>
<span class="nb">Require</span> <span class="k">all</span> granted
<span class="nt">&lt;/Files&gt;</span>
<span class="nt">&lt;/Directory&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-serving-the-admin-files">
<span id="s-id3"></span><span id="serving-the-admin-files"></span><span id="id3"></span><h2>服务后台文件<a class="headerlink" href="#serving-the-admin-files" title="永久链接至标题">¶</a></h2>
<p><a class="reference internal" href="../../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 中包含 <a class="reference internal" href="../../../ref/contrib/staticfiles.html#module-django.contrib.staticfiles" title="django.contrib.staticfiles: An app for handling static files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code></a> 时，Django 开发服务器自动为这些归属于后台应用（也包含其它已安装的应用）的静态文件提供服务。这与你使用其它服务器时不太一样。你需要正确配置 Apache 或其它你使用的 Web 服务器，另其正确的为后台文件提供服务。</p>
<p>后台文件位于 Django 发行版的 (<code class="file docutils literal notranslate"><span class="pre">django/contrib/admin/static/admin</span></code>) 中。</p>
<p>我们 <strong>强烈</strong> 建议用 <a class="reference internal" href="../../../ref/contrib/staticfiles.html#module-django.contrib.staticfiles" title="django.contrib.staticfiles: An app for handling static files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.staticfiles</span></code></a> 处理后台文件（连同上一节所述的 Web 服务器；这意味着用 <a class="reference internal" href="../../../ref/contrib/staticfiles.html#django-admin-collectstatic"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">collectstatic</span></code></a> 管理命令收集 <a class="reference internal" href="../../../ref/settings.html#std:setting-STATIC_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_ROOT</span></code></a> 中的静态文件，然后配置 Web 服务器，使其在 <a class="reference internal" href="../../../ref/settings.html#std:setting-STATIC_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_URL</span></code></a> 为 <a class="reference internal" href="../../../ref/settings.html#std:setting-STATIC_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_ROOT</span></code></a> 提供服务），不过，这还有几个方法：</p>
<ol class="arabic simple">
<li>在文档根目录中创建一个指向后台静态文件的符号链接（Apache 配置中可能要添加 <code class="docutils literal notranslate"><span class="pre">+FollowSymLinks</span></code>）。</li>
<li>使用前文介绍的 <code class="docutils literal notranslate"><span class="pre">Alias</span></code> 指令，为合适的 URL (可能是 <a class="reference internal" href="../../../ref/settings.html#std:setting-STATIC_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_URL</span></code></a> + <code class="docutils literal notranslate"><span class="pre">admin/</span></code>) 取个别名，指向后台文件的实际位置。</li>
<li>直接将后台静态文件拷贝至 Apache 的文档根目录。</li>
</ol>
</div>
<div class="section" id="s-authenticating-against-django-s-user-database-from-apache">
<span id="authenticating-against-django-s-user-database-from-apache"></span><h2>Apache 利用 Django 的用户数据库进行验证<a class="headerlink" href="#authenticating-against-django-s-user-database-from-apache" title="永久链接至标题">¶</a></h2>
<p>Django 提供了一个处理器，允许 Apache 直接用 Django 的认证授权后端认证用户。参考文档 <a class="reference internal" href="apache-auth.html"><span class="doc">mod_wsgi 认证授权文档</span></a>。</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">如何使用 Apache 和 <code class="docutils literal notranslate"><span class="pre">mod_wsgi</span></code> 托管 Django</a><ul>
<li><a class="reference internal" href="#basic-configuration">基础配置</a></li>
<li><a class="reference internal" href="#using-mod-wsgi-daemon-mode">使用 <code class="docutils literal notranslate"><span class="pre">mod_wsgi</span></code> 后台模式</a></li>
<li><a class="reference internal" href="#serving-files">提供文件服务</a></li>
<li><a class="reference internal" href="#serving-the-admin-files">服务后台文件</a></li>
<li><a class="reference internal" href="#authenticating-against-django-s-user-database-from-apache">Apache 利用 Django 的用户数据库进行验证</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="uwsgi.html"
                        title="上一章">如何用 uWSGI 托管 Django</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="apache-auth.html"
                        title="下一章">Apache 利用 Django 的用户数据库进行验证</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../../_sources/howto/deployment/wsgi/modwsgi.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="uwsgi.html" title="如何用 uWSGI 托管 Django">previous</a>
     |
    <a href="../../index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="apache-auth.html" title="Apache 利用 Django 的用户数据库进行验证">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>